<template>
  <div class=""></div>
</template>

<script>
export default {
  props: {},
  components: {},
  data() {
    return {};
  },
  created() {
    this.initDataFun(); // 初始化数据
  },
  mounted() {},
  beforeDestroy() {},
  computed: {},
  watch: {},
  methods: {
    // #region Promise测验
    // 初始化数据
    initDataFun(toDoFunc) {
      this.timeOutPromise({ toDoFunc: toDoFunc });
      this.conditionalJudgment();
      this.httpFun();
    },
    /**
     * @param: toDoFunc // 要执行的方法
     * @param: successFunc // 执行的方法成功后要做的事
     * @param: errorFunc // 执行的方法失败时要做的事
     * setTimeout// 模拟延时
     * async await// 异步等待
     */
    // 类似请求、执行传入方法的
    timeOutPromise({ toDoFunc, successFunc, errorFunc }) {
      return new Promise((resolve, reject) => {
        setTimeout(async () => {
          try {
            await toDoFunc();
            resolve('success');
          } catch (err) {
            reject(new Error(err));
          }
        }, 1000);
      })
        .then((res) => {
          console.log(res);
          if (successFunc) successFunc();
        })
        .catch((err) => {
          console.error(err);
          if (errorFunc) errorFunc();
        });
    },
    // 类似条件判断的
    conditionalJudgment() {
      return new Promise((resolve, reject) => {
        let a = 1;
        if (a) {
          resolve('success');
        } else {
          reject(new Error('a is not meet the conditions'));
        }
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // all,race
    async httpFun() {
      const p1 = new Promise((resolve) => {
        setTimeout(() => {
          resolve('ok1');
        }, 1000);
      });
      const p2 = new Promise((resolve) => {
        setTimeout(() => {
          // reject('err2');
          resolve('ok2');
        }, 1000);
      });
      // const res = await Promise.all([p1, p2]);
      const res = await Promise.race([p1, p2]);
      console.log(res);
    },
    // #endregion
  },
};
</script>

<style lang="less"></style>

<style lang="less" scoped></style>
